<?php

    require_once "./libray/page.php";
    $getParam = $_GET;
    if(empty($getParam)){
        exit('非法访问，退出登录');
    }
    $nowRedis = new Redis();
    //$nowRedis->auth('root');
    $nowRedis->connect("localhost",6379);
    switch ($getParam["model"]){
        case 'register':
            $nowData = $_POST;
            //第一步，链接数据库
            $link = @mysqli_connect("localhost","root","root","messageBoard","3306");
            //第二步，判断链接
            if(mysqli_connect_errno()){
                exit("链接失败，原因：".mysqli_connect_error());
            }
            //第三步，设置字符集。
            mysqli_set_charset($link,"utf8");
            //第四步，判断字符集是否设置成功；
            if(mysqli_errno($link)){
                exit("字符集设置失败，原因：".mysqli_error($link));
            }
            $sql = "select * from `userList` where `userName` = '".$nowData["userName"]."'";

            //第六步，执行sql；
            $result = mysqli_query($link,$sql);
            $xxx = mysqli_fetch_row($result);
            if(!empty($xxx)){
                echo json_encode(["code"=>2,"msg"=>"账户名已经存在"]);
            }else {
                //第五步，拼接sql;`person`
                $fieldStr = '';
                $valueStr = '';
                foreach ($nowData as $key => $value) {
                    $fieldStr .= "`{$key}`,";
                    $valueStr .= "'{$value}',";
                }

                $fieldStr = substr($fieldStr, 0, -1);
                $valueStr = substr($valueStr, 0, -1);

                $sql = sprintf("insert into `userList`(%s) values(%s)", $fieldStr, $valueStr);
                //第六步，执行sql；
                $result = mysqli_query($link, $sql);
                //第七步上，查询；
                $arr = [];
//                while($row=mysqli_fetch_assoc($result)){
//                    $arr[]=$row;
//                }
                //第七步下，操作；
                if ($result) {
                    echo json_encode(["code" => 1, "msg" => "增加成功"]);
                } else {
                    echo json_encode(["code" => 2, "msg" => "增加失败"]);
                }
                //第八步，关闭链接，释放资源。
                mysqli_close($link);
            }
        break;//注册

        case 'login' :
            $nowData = $_POST;
            //第一步，链接数据库
            $link = @mysqli_connect("localhost","root","root","messageBoard","3306");
            //第二步，判断链接
            if(mysqli_connect_errno()){
                exit("链接失败，原因：".mysqli_connect_error());
            }
            //第三步，设置字符集。
            mysqli_set_charset($link,"utf8");
            //第四步，判断字符集是否设置成功；
            if(mysqli_errno($link)){
                exit("字符集设置失败，原因：".mysqli_error($link));
            }
            $sql = "select * from `userList` where `userName` = '".$nowData["userName"]."' and `password` = '".$nowData["password"]."'";

            //第六步，执行sql；
            $result = mysqli_query($link,$sql);
            $oneRow = mysqli_fetch_assoc($result);
            $loginUser = $nowData['userName'];
            $errTotal = $nowRedis->get($loginUser);
            if($errTotal>4){
                echo json_encode(["code"=>2,"msg"=>"汤唯"]);
                die;
            }
            if(empty($oneRow)){
                if(false == $errTotal ){
                    $nowTime = time();
                    $midnight = mktime(23, 59, 59, date('m'), date('d'), date('Y'));
                    $difference = $midnight - $nowTime;
                    $nowRedis->set($loginUser,1,$difference);

                }else{
                    $nowRedis->incr($loginUser);
                }
                echo json_encode(["code"=>2,"msg"=>"fail"]);
            }else {
                setcookie('loginUser',$xxx["userName"],time()+30000000000);
                echo json_encode(["code" => 1, "msg" => "login,success"]);
            }
            //第八步，关闭链接，释放资源。
            mysqli_close($link);
        break;//登录

        case 'newest' ://最新发帖

            $nowData = $nowRedis->lRange('list',0,9);
            if(empty($nowData)){
                echo json_encode(["code"=>2,"msg"=>"最新查询错误"]);
            }else {
                echo json_encode(["code" => 1, "msg" => "查询成功",'newData'=>$nowData]);
            }
        break;

        case 'articleShow':
            //第一步，链接数据库
            $link = @mysqli_connect("localhost","root","root","messageBoard","3306");
            //第二步，判断链接
            if(mysqli_connect_errno()){
                exit("链接失败，原因：".mysqli_connect_error());
            }
            //第三步，设置字符集。
            mysqli_set_charset($link,"utf8");
            //第四步，判断字符集是否设置成功；
            if(mysqli_errno($link)){
                exit("字符集设置失败，原因：".mysqli_error($link));
            }
            $sql = "select * from `article`";// order by `create_at` desc;
            $result = mysqli_query($link,$sql);
            $data = [];
            while ($row = mysqli_fetch_assoc($result)){
                $data[]=$row;
            }
            $dataCount = mysqli_num_rows($result);
            defined("NUM") OR define("NUM",4);
            $pageCount = ceil($dataCount/NUM);

            $nowPage = isset($_POST["page"]) ? $_POST["page"] : 1;
            // $nowPage = $_POST["page"];
            if($pageCount < $nowPage && $nowPage < 0){
                $nowPage = 1;
            }
            $start = NUM * ($nowPage - 1);
            $dataSmall = array_slice($data,$start,NUM);
            $html = "";
            if($nowPage>1){
                $html .= "<a style='color: blue' href='#' onclick='press(1)'>首页</a>&nbsp&nbsp";
                $html .= "<a style='color: blue' href='#' onclick='press({$nowPage}-1)'>上一页</a>&nbsp&nbsp";
            }else{
                $html .= "<span style='color: blue'>首页</span>&nbsp&nbsp";
                $html .= "<span style='color: blue'>上一页</span>&nbsp&nbsp";
            }
            $longest = 5;
            $padding = ($longest-1)/2;
            $forStart  = $nowPage - $padding < 1 ? 1 : $nowPage - $padding;
            $forEnd = $nowPage + $padding > $pageCount ? $pageCount : $nowPage + $padding;
            for($i=$forStart;$i<=$forEnd;$i++){
                if($nowPage == $i){
                    $html .= "<span style='color: blue'>{$i}</span>&nbsp&nbsp";
                }else{
                    $html .= "<a style='color: blue' href='#' onclick='press({$i})'>{$i}</a>&nbsp&nbsp";
                }
            }
            if($nowPage<$pageCount){
                $html .= "<a style='color: blue' href='#' onclick='press({$nowPage}+1)'>下一页</a>&nbsp&nbsp";
                $html .= "<a style='color: blue' href='#' onclick='press({$pageCount})'>尾页</a>&nbsp&nbsp";
            }else{
                $html .= "<span style='color: blue'>下一页</span>&nbsp&nbsp";
                $html .= "<span style='color: blue'>尾页</span>&nbsp&nbsp";
            }
            echo json_encode(["code"=>1,"msg"=>"分页成功","smallData"=>$dataSmall,"html"=>$html]);
        break;//展示所以

        case 'plusArticle':
            $nowData = $_POST;
            $nowData["create_at"] = time();
            //第一步，链接数据库
            $link = @mysqli_connect("localhost","root","root","messageBoard","3306");
            //第二步，判断链接
            if(mysqli_connect_errno()){
                exit("链接失败，原因：".mysqli_connect_error());
            }
            //第三步，设置字符集。
            mysqli_set_charset($link,"utf8");
            //第四步，判断字符集是否设置成功；
            if(mysqli_errno($link)){
                exit("字符集设置失败，原因：".mysqli_error($link));
            }
            //第五步，拼接sql;`person`
            $fieldStr = '';
            $valueStr = '';
            foreach ($nowData as $key => $value) {
                $fieldStr .= "`{$key}`,";
                $valueStr .= "'{$value}',";
            }

            $fieldStr = substr($fieldStr, 0, -1);
            $valueStr = substr($valueStr, 0, -1);

            $sql = sprintf("insert into `article`(%s) values(%s)", $fieldStr, $valueStr);
            //第六步，执行sql；
            $result = mysqli_query($link, $sql);
            //第七步上，查询；
            $arr = [];
//                while($row=mysqli_fetch_assoc($result)){
//                    $arr[]=$row;
//                }
            //第七步下，操作；
            if ($result) {
                $nowRedis->lPush('list',$nowData["titled"]);
                echo json_encode(["code" => 1, "msg" => "增加成功"]);
            } else {
                echo json_encode(["code" => 2, "msg" => "增加失败"]);
            }
            //第八步，关闭链接，释放资源。
            mysqli_close($link);

        break;//增加文章

        default:
            echo '郑州开发中';
        break;
    }

?>

